import React, { Component } from 'react';
import '../../styles/Login/login.scss';
import 'antd-mobile/dist/antd-mobile.css';
import { Button, Toast, } from 'antd-mobile';
import { Link } from "react-router-dom";
import { loginCheck } from "../../api/login";
import { testUser, testPass,  } from "../../utils/RegExp";

export default class Login extends Component {
  onLogin = () => {
    if (this.agreement.checked) {//先判断是否勾选协议
      if (testUser(this.user.value) && testPass(this.pass.value)) {//在判断账号密码格式是否正确
        let _this = this;
        async function getLoginCheck() {
          let result = await Promise.resolve(loginCheck({ username: _this.user.value, password: _this.pass.value }))
          console.log(result);
          if (result.status === 0) {//请求成功status为0
            // 修改登录状态
            _this.props.changeShow(true)
            // 登录后将信息本地缓存
            localStorage.setItem("token", result.wdata.oauth_token)
            // 请求回来的数据存到仓库
            _this.props.saveUserInfo(result.wdata)
            console.log(_this.props.state.Login.userInfo)
            Toast.success(result.msg, 1);
          } else {
            Toast.fail(result.msg, 1);
          }
        }
        getLoginCheck();
      } else {
        Toast.info('账号或密码格式错误', 1);
      }
    } else {
      Toast.info('请勾选协议', 1);
    }
  }

  mobileVerify = () => {
    // 手机号验证
    if (testUser(this.user.value)) {
      this.user.style.borderBottom = '0.02rem solid #C9C9C9 '
    } else {
      this.user.style.borderBottom = '0.02rem solid red'
      Toast.info('手机号码格式错误，请重新输入!!!', 1);
    }
  }
  passVerify = () => {
    // 密码验证
    if (testPass(this.pass.value)) {
      this.pass.style.borderBottom = '0.02rem solid #C9C9C9'
    } else {
      this.pass.style.borderBottom = '0.02rem solid red'
      Toast.info('密码必须位6-20数，至少包含数字跟字母，可以有字符', 1);
    }
  }

  render() {
    return (
      <div className="login-wrap">
        <div className="login-box">
          <div className="input-box">
            <input placeholder="请输入手机号" onBlur={this.mobileVerify} ref={c => this.user = c} type="text" defaultValue='13670868807' />
            <input placeholder="请输入密码" onBlur={this.passVerify} ref={c => this.pass = c} type="password" defaultValue='123456' />
          </div>
          <div>
            <input ref={c => this.agreement = c}  type="checkbox"/>
            <span>&nbsp; &nbsp;同意《<a href="##">用户服务协议</a>》</span>
          </div>
          <Button type="primary" className="login-button" onClick={this.onLogin}>登录</Button>
          <div className="bottom-button">
            <Link to="/rgister">注册</Link>
            <Link to="/forget">忘记密码</Link>
          </div>
        </div>
      </div>
    )
  }
}
